package data;

import haxe.Json;
import json2object.JsonParser;
import tree.Root;
import hxd.File;
import tree.Leaf;
import tree.LeafKind;
import tree.Tress;

class Root_Data extends Tress {
    public function new() {
        super();
        AddLeaf(DCanvas, new Data_Canvas());
        AddLeaf(DBook, new Data_Book());
    }
    
    public override function OnEnter(last:LeafKind) {
        super.OnEnter(last);
        var keys = m_leafMap.keys();
        for (key in keys){
            PushLeaf(key);
        }
    }

    public function SaveData() {
        var data_sl = new InnerData_SL();
        Save(data_sl);
        var json = Json.stringify(data_sl);
        sys.io.File.saveContent("temp.json", json);
    }

    public function LoadData() {
        File.browse(function(e) {
           var path = e.fileName;
           if(path == "" || path == null){
               return;
           } 
           var json = sys.io.File.getContent(path);
           var data_sl = new JsonParser<InnerData_SL>().fromJson(json);
            Load(data_sl);
        });
        
    }


    private function Save(data_sl:InnerData_SL) {
        var values = m_leafMap.iterator();
        for (value in values){
            var data : Data = cast value;
            if(data != null){
                data.Save(data_sl);
            }
        }
    }

    private function Load(data_sl:InnerData_SL) {
        var values = m_leafMap.iterator();
        for (value in values){
            var data : Data = cast value;
            if(data != null){
                data.Load(data_sl);
            }
        }
    }
}